/*
 * Copyright (c) 2018 maoyan.com
 * All rights reserved.
 *
 */
package com.darren.euc.action.app;

import com.alibaba.fastjson.JSONArray;
import com.darren.euc.dao.SpaceDao;
import com.darren.euc.entity.*;
import com.darren.euc.job.ActivityTask;
import com.darren.euc.job.HaqiTask;
import com.darren.euc.job.MeetRoomOrderTask;
import com.darren.euc.job.NoticeTask;
import com.darren.euc.repository.DeptRepository;
import com.darren.euc.repository.MeetingRoomRepository;
import com.darren.euc.repository.MemberRepository;
import com.darren.euc.service.*;
import com.darren.euc.util.DateUtil;
import com.darren.euc.util.GenegateDomainUtil;
import com.darren.euc.util.PropertyConfigurer;
import com.darren.euc.util.PropertyHelper;
import com.darren.euc.util.haqi.HaquAPIHandler;
import com.darren.euc.util.haqi.request.*;
import com.google.common.collect.Lists;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.darren.euc.util.GenegateDomainUtil.isAvaliable;

/**
 * APP接口 线上运营相关
 *
 * @author fangwenhao
 * @created 2018/3/12
 */
@Controller
@RequestMapping("/_onlineops")
public class _OnlineOpsAction {

    private static final Log log = LogFactory.getLog(_OnlineOpsAction.class);

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityMemberRelService activityMemberRelService;

    @Autowired
    private MeetingroomOrderService meetingroomOrderService;

    @Autowired
    private MeetingRoomRepository meetingRoomRepository;

    @Autowired
    private ServiceTelService serviceTelService;

    @Autowired
    private HaqiRecordService haqiRecordService;

    @Autowired
    private ClientParamsEntityService clientParamsEntityService;

    @Autowired
    private MemberRepository memberRepository;

    @Autowired
    private DeptRepository deptRepository;

    @Autowired
    private HaqiTask haqiTask;

    @Autowired
    private ActivityTask activityTask;

    @Autowired
    private NoticeTask noticeTask;

    @Autowired
    private MeetRoomOrderTask meetRoomOrderTask;

    @Autowired
    private SpaceDao spaceDao;

    /**
     * 查询考勤记录-web实时
     * @param requestParams
     * @param request
     * @return
     */
    @RequestMapping(value = "/workontime/query")
    @ResponseBody
    public ResponseJSON getWorkFindOnTime(WorkFindOntimeRequest requestParams, HttpServletRequest request){
        requestParams.setAppCode(PropertyConfigurer.getPropertiesStr("haqi.appcode"));
        Member member = (Member) request.getAttribute("member");
        Long[] userIds = requestParams.getUserIds();
        if (userIds.length != 1 || !isAvaliable()){
            return new ResponseJSON().set(-3,"入参异常",null);
        }
        if (userIds[0] == 0L){
            List<Member> members = memberRepository.findByClientId(member.getClientId());
            if (CollectionUtils.isEmpty(members) || !isAvaliable()){
                return new ResponseJSON().set(-4,"空数据",null);
            }
            List<Long> faceUserIds = Lists.newArrayList();
            for (Member m : members){
                if (m.getFaceUserId() != null){
                    faceUserIds.add(m.getFaceUserId());
                }
            }
            if (CollectionUtils.isEmpty(faceUserIds)){
                ResponseJSON responseJSON = new ResponseJSON();
                responseJSON.set(-4,"空数据",null);
                return new ResponseJSON().set(-4,"空数据",null);
            }
            Long[] faceUserIdArr = faceUserIds.toArray(new Long[0]);
            requestParams.setUserIds(faceUserIdArr);
        }else {
            requestParams.setUserIds(userIds);
        }
        String result = HaquAPIHandler.getWorkFind(requestParams);
        log.info(result);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        if (!code.equals("2000")){
            String msg = jsonObject.getString("message");
            return new ResponseJSON().set(-5,msg,null);
        }
        Integer totalElements = jsonObject.getJSONObject("data").getInteger("totalElements");
        Integer totalPages = jsonObject.getJSONObject("data").getInteger("totalPages");
        PageBean pageBean = new PageBean();
        pageBean.setTotalRow(totalElements);
        pageBean.setCurrentPage(requestParams.getIndex());
        pageBean.setPageSize(requestParams.getSize());
        pageBean.setTotalPage(totalPages);
        JSONArray content = jsonObject.getJSONObject("data").getJSONArray("content");
        List<HaqiDTO> haqiDTOList;
        if (content.isEmpty()){
            haqiDTOList = Collections.emptyList();
        }
        haqiDTOList = JSONArray.parseArray(content.toString(),HaqiDTO.class);
        List<HaqiVO> haqiVOList = Lists.newArrayList();
        for (HaqiDTO haqiDTO : haqiDTOList){
            HaqiVO haqiVO = new HaqiVO();
            Long faceUserId = haqiDTO.getFaceUserId();
            Member mem = memberRepository.findByFaceUserId(faceUserId);
            if (mem == null){
                continue;
            }
            if (mem.getDeptId() == 0){
                haqiVO.setDeptName("");//表示无部门
            }else {
                Dept dept = deptRepository.findOne(mem.getDeptId());
                if (dept == null){
                    haqiVO.setDeptName("未定义");
                }else {
                    haqiVO.setDeptName(dept.getDeptName());
                }
            }
            haqiVO.setId(haqiDTO.getId());
            haqiVO.setUserName(haqiDTO.getUserName());
            haqiVO.setDate(haqiDTO.getDate());
            haqiVO.setCheckInTime(haqiDTO.getCheckInTime());
            haqiVO.setCheckOutTime(haqiDTO.getCheckOutTime());
            haqiVO.setStatus1(haqiDTO.getCheckInTime() == null ? 0 :judgeInJobTime(haqiDTO.getCheckInTime(),haqiDTO.getFaceUserId()));
            haqiVO.setStatus2(haqiDTO.getCheckOutTime() == null ? 0 :judgeInJobTime(haqiDTO.getCheckOutTime(),haqiDTO.getFaceUserId()));
            haqiVOList.add(haqiVO);
        }
        pageBean.setList(haqiVOList);
        pageBean.init();
        return new ResponseJSON().setData(pageBean);
    }

    /**
     * 考勤记录
     * @param requestParams
     * @param request
     * @return
     */
    @RequestMapping(value = "/getWorkFind")
    @ResponseBody
    public String getFindWork(WorkFindRequest requestParams,HttpServletRequest request){
        requestParams.setAppCode(PropertyConfigurer.getPropertiesStr("haqi.appcode"));
        String result = HaquAPIHandler.getWorkFind(requestParams);
        System.out.println(request);
        return result;
    }

    /**
     * 查询考勤
     * @param requestJson
     * @param response
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/worktime/query",method = RequestMethod.POST)
    public ResponseJSON queryWorktime(@RequestBody JSONObject requestJson, HttpServletResponse response, HttpServletRequest request){

        Member member = (Member) request.getAttribute("member");
        JSONObject data = requestJson.getJSONObject("data");
        data.put("clientId",member.getClientId());
        PageBean pageBean = haqiRecordService.queryRecordByPage(data,member, PropertyHelper.getPageSize(), requestJson.getInt("currentPage"));
        if (pageBean == null || !isAvaliable()){
            return new ResponseJSON(-3,"脏数据",null);
        }
        return new ResponseJSON().setData(pageBean);
    }

    /**
     * 备用接口
     * @param date yyyy-MM-dd
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/workTask",method = RequestMethod.GET)
    public ResponseJSON workTask(@RequestParam String date){
        GenegateDomainUtil.setDateTime(date);
        // 公告状态
        noticeTask.refreshNoticeStatus();
        // 会议状态
        meetRoomOrderTask.refreshMeetingroomOrderStatus();
        // 活动状态
        activityTask.refreshActivityStatus();
        // 考勤记录
        haqiTask.syncCurrHaqiRecord(date);
        return new ResponseJSON();
    }

    /**
     * 考勤记录,查询单月
     * @param requestParams
     * @param request
     * @return
     */
    @RequestMapping(value = "/getWorkFindByMonth")
    @ResponseBody
    public ResponseJSON getWorkFindByMonth(WorkFindRequest requestParams,HttpServletRequest request){
        Member member = (Member) request.getAttribute("member");
        HaqiRecordResp haqiRecordResp = haqiRecordService.querybmV2(requestParams.getStart(),requestParams.getEnd(),member.getId());
        return new ResponseJSON().setData(haqiRecordResp);
    }


    /**
     * 考勤记录,查询单天
     * @param requestParams
     * @param request
     * @return
     */
    @RequestMapping(value = "/getWorkFindByDay")
    @ResponseBody
    public ResponseJSON getWorkFindByDay(WorkFindRequest requestParams,HttpServletRequest request){
        Member member = (Member) request.getAttribute("member");
        HaqiRecord haqiRecord = haqiRecordService.querybdV2(requestParams.getStart(),requestParams.getEnd(),member.getId());
        if (haqiRecord == null || !isAvaliable()){
            return new ResponseJSON(-3,"本日无考勤信息或用户信息异常",null);
        }
        return new ResponseJSON().setData(haqiRecord);
    }

    /**
     * 备注考勤原因
     * @param id，HaqiRecord的id参数
     * @param reason 原因
     * @param type  首次打卡1 末次打卡2
     * @param request
     * @return
     */
    @RequestMapping(value = "/workReason")
    @ResponseBody
    public ResponseJSON workReason(@RequestParam Long id, @RequestParam String reason, @RequestParam Integer type, HttpServletRequest request){
        HaqiRecord haqiRecord = haqiRecordService.workReason(id,reason,type);
        if (haqiRecord == null){
            return new ResponseJSON(-3,"已备注过原因",null);
        }
        return new ResponseJSON().setData(haqiRecord);
    }

    /**
     *
     * API名称：获取识别历史记录
     * @param requestParams
     * @param request
     * @return
     */
    @RequestMapping(value = "/getRecognitionHistory")
    @ResponseBody
    public String getRecognitionHistory(RecognitionHistoryRequest requestParams, HttpServletRequest request){
        requestParams.setAppCode(PropertyConfigurer.getPropertiesStr("haqi.appcode"));
        String result = HaquAPIHandler.getRecognitionHistory(requestParams);
        System.out.println(request);
        return result;
    }

    /**
     * 人脸信息
     * @param requestParams
     * @param request
     * @return
     */
    @RequestMapping(value = "/getFace")
    @ResponseBody
    public String getFace(GetFaceRequest requestParams, HttpServletRequest request){
       // requestParams.setAppCode(PropertyConfigurer.getPropertiesStr("haqi.appcode"));
        Member member =  (Member) request.getAttribute("member");
        if(member==null){
            return ResponseJSON.defaultFailedResponse().toString();
        }
        requestParams.setUserId(String.valueOf(member.getId()));
        String result = HaquAPIHandler.getFace(requestParams);
        System.out.println(request);
        return result;
    }
    /**
     * 得到设备信息
     * @param requestParams
     * @param request
     * @return
     */
    @RequestMapping(value = "/getGetDeviceList")
    @ResponseBody
    public String getGetDeviceList(GetDeviceListRequest requestParams, HttpServletRequest request){
        requestParams.setAppCode(PropertyConfigurer.getPropertiesStr("haqi.appcode"));
        String result = HaquAPIHandler.getGetDeviceList(requestParams);
        System.out.println(request);
        return result;
    }
    /**
     * 获取公告
     */
    @ResponseBody
    @RequestMapping(value = "/getNotice")
    public ResponseJSON getNotice(@RequestParam(name = "pn", required = false, defaultValue = "1") Integer pn,
            @RequestParam(name = "ps", required = false, defaultValue = "10") Integer ps, HttpServletRequest request) {
        Member member = (Member) request.getAttribute("member");
        List<Long> spaceIds = Lists.newArrayList(member.getSpaceId().longValue(), 0l);
        PageBean pageBean = noticeService.findNotice(spaceIds, ps, pn);
        return new ResponseJSON().setData(pageBean);
    }

    /**
     * 查看公告
     */
    @ResponseBody
    @RequestMapping(value = "/getOneNotice")
    public ResponseJSON getOneNotice(@RequestParam(name = "notice_id") Long noticeId, HttpServletRequest request) {
        Notice notice = noticeService.findById(noticeId);
        return new ResponseJSON().setData(notice);
    }

    /**
     * 公告详情H5
     */
    @RequestMapping(value = "/notice_detail")
    public void noticeDetail(@RequestParam(name = "notice_id") long notice_id, Model model) {
        Notice notice = noticeService.findById(notice_id);
        model.addAttribute("notice", notice);
    }

    /**
     * 活动详情H5
     * 
     * @param activity_id
     * @param model
     */
    @RequestMapping(value = "/activity_detail")
    public void activityDetail(@RequestParam(name = "activity_id") long activity_id, Model model) {
        Activity activity = activityService.findById(activity_id);
        Integer count = activityMemberRelService.findByActivityId(activity_id).size();
        ActivityVO activityVO = new ActivityVO(activity);
        activityVO.setLeftCount(activity.getMaxCount() - count);
        model.addAttribute("bean", activityVO);
    }

    /**
     * 获取精彩活动
     */
    @ResponseBody
    @RequestMapping(value = "/getActivity")
    public ResponseJSON getActivity(@RequestParam(name = "pn", required = false, defaultValue = "1") Integer pn,
            @RequestParam(name = "ps", required = false, defaultValue = "10") Integer ps,
            @RequestParam(name = "only_mine", required = false, defaultValue = "0") Integer onlyMine,
            HttpServletRequest request) {
        Member member = (Member) request.getAttribute("member");
        if (onlyMine == 0) {
            Integer spaceId = member.getSpaceId();
            List<Long> data = new ArrayList<>();
            data.add(0l);
            data.add(spaceId.longValue());
            PageBean pageBean = activityService.queryForPageActivitySpaceHQL(data, ps, pn);
            return new ResponseJSON().setData(pageBean);
        } else {
            Integer memberId = member.getId();
            PageBean pageBean = activityService.queryForPageActivityByMemberSQL(memberId, ps, pn);
            return new ResponseJSON().setData(pageBean);
        }
    }

    /**
     * 查看单个活动
     */
    @ResponseBody
    @RequestMapping(value = "/getOneActivity")
    public ResponseJSON getOneActivity(@RequestParam(name = "activity_id", required = true) Long activityId,
            HttpServletRequest request) {
        Activity activity = activityService.findById(activityId);
        Integer count = activityMemberRelService.findByActivityId(activityId).size();
        ActivityVO activityVO = new ActivityVO(activity);
        activityVO.setLeftCount(activity.getMaxCount() - count);
        return new ResponseJSON().setData(activityVO);
    }

    /**
     * 我要报名
     */
    @ResponseBody
    @RequestMapping(value = "/checkName")
    public ResponseJSON checkName(@RequestParam(name = "activity_id", required = true) Long activityId,
            HttpServletRequest request) {
        Member member = (Member) request.getAttribute("member");
        Integer memberId = member.getId();
        ActivityMemberRel activityMemberRel = new ActivityMemberRel();
        activityMemberRel.setActivityId(activityId);
        activityMemberRel.setMemberId(memberId.longValue());
        activityMemberRel.setStatus(1);
        activityMemberRel.setIsCheck(0);
        activityMemberRel.setAddTime(new Date());
        activityMemberRel.setModTime(new Date());
        Activity activity = activityService.findById(activityId);
        Integer employStatus = member.getEmployStatus();
        Integer activityUnvip = activity.getIsUnVip();
        if(activityUnvip ==0 && employStatus!=1){
        	return new ResponseJSON(-1, "非入驻会员不能参与报名", null);
        }
        
        //查询是否已经报名
        ActivityMemberRel dbMember = activityMemberRelService.findByActivityIdAndMemberId(activityId,memberId);
        if(dbMember!=null || !isAvaliable()){
            return new ResponseJSON(-1, "已经报名过了", null);
        }
        Integer count = activityMemberRelService.findByActivityId(activityId).size();
        if (activity.getMaxCount() > count && activity.getStatus() == 1) {
            activityMemberRelService.save(activityMemberRel);
            return new ResponseJSON();
        } else {
            return new ResponseJSON(-3, "已报满或已结束"+employStatus+activityUnvip, null);
        }
    }

    /**
     * 获取待办
     */
    @ResponseBody
    @RequestMapping(value = "/getTodos")
    public ResponseJSON getTodos(@RequestParam(name = "pn", required = false, defaultValue = "1") Integer pn,
            @RequestParam(name = "ps", required = false, defaultValue = "10") Integer ps, HttpServletRequest request) {
        Member member = (Member) request.getAttribute("member");
        List<ActivityMemberRel> activityMemberRels = activityMemberRelService.findByMemberIdAndStatusIn(member.getId().longValue(),
                Lists.newArrayList(1));
        List<Activity> activityList = Lists.newArrayList();
        if (activityMemberRels.size() >= 0) {
            List<Long> longList = activityMemberRels.stream().map(ActivityMemberRel::getActivityId)
                    .collect(Collectors.toList());
            activityList = activityService.findByIdIn(longList);
        }
        List<MeetingroomOrder> meetingroomOrderList = meetingroomOrderService
                .findBySpaceIdAndStatusAndPayStatusNotAndDayGreaterThanEqual(member.getSpaceId(), 1,0,
                        new DateTime().withMillisOfDay(0).toDate());
        List<MeetingroomOrder> todoOrderList = Lists.newArrayList();
        if (meetingroomOrderList.size() > 0) {
            todoOrderList = meetingroomOrderList.stream().filter(meetingroomOrder -> JSONArray
                    .parseArray(meetingroomOrder.getMemList(), Integer.class).contains(member.getId())).collect(Collectors.toList());
        }
        List<TODO> todos = Lists.newArrayList();
        for (Activity activity : activityList){
            TODO todo = new TODO();
            todo.setId(activity.getId().intValue());
            todo.setType(1);
            todo.setTitle(activity.getTitle());
            Space space = spaceDao.findById(member.getSpaceId());
            if (space!=null){
                todo.setSpaceName(space.getSpaceName());
            }
            todo.setCount(activityList.size());
            todo.setDate(new DateTime(activity.getAddTime()).toString("yyyy-MM-dd HH:mm:ss"));
            todo.setStartTime(new DateTime(activity.getBeginTime()).toString("yyyy-MM-dd HH:mm:ss"));
            todo.setEndTime(new DateTime(activity.getEndTime()).toString("yyyy-MM-dd HH:mm:ss"));
            todos.add(todo);
        }
        for (MeetingroomOrder meetingroomOrder : todoOrderList){
            TODO todo = new TODO();
            Meetingroom meetingroom = meetingRoomRepository.findOne(meetingroomOrder.getRoomId());
            if (meetingroom == null){
                continue;
            }
            todo.setId(meetingroom.getId());
            todo.setType(2);
            todo.setTitle(meetingroomOrder.getSubject());
            Space space = spaceDao.findById(member.getSpaceId());
            if (space!=null){
                todo.setSpaceName(space.getSpaceName());
            }
            todo.setRoomName(meetingroom.getMeetingroomName());
            todo.setMoney(meetingroomOrder.getMoney().toString());
            todo.setCount(JSONArray.parseArray(meetingroomOrder.getMemList(),Integer.class).size());
//            if (!StringUtil.isEmptyOrWhitespace(meetingroom.getSeatCount())){
//                todo.setCount(Integer.valueOf(meetingroom.getSeatCount()));
//            }
            todo.setDate(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd HH:mm:ss"));
            List<BookTimeRange> timeRanges = JSONArray.parseArray(meetingroomOrder.getRangeList(),BookTimeRange.class);
            if (!CollectionUtils.isEmpty(timeRanges)){
                todo.setStartTime(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " " + timeRanges.get(0).getTime() + ":00");
                todo.setEndTime(new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " " + DateUtil.addHalfHour(timeRanges.get(timeRanges.size()-1).getTime()) + ":00");
            }
            todo.setFacilities(meetingroom.getOtherFacilities());
            todos.add(todo);
        }
        PageBean pageBean = new PageBean();
        pageBean.setTotalRow(todos.size());
        pageBean.setCurrentPage(pn);
        pageBean.setTotalPage(todos.size()/pn+1);
        pageBean.setPageSize(ps);
        Integer size = todos.size();
        if (pn*ps >= size){
            pageBean.setList(todos.subList((pn-1)*ps,size));
        }else {
            pageBean.setList(todos.subList((pn-1)*ps,pn*ps));
        }
        pageBean.init();
        return new ResponseJSON().setData(pageBean);
    }

    /**
     * 我的会议 -1 全部 0 已取消 1 未开始 2 已结束 3 进行中
     */
    @ResponseBody
    @RequestMapping(value = "/getMyMeeting")
    public ResponseJSON getMyMeeting(@RequestParam(name = "pn", required = false, defaultValue = "1") Integer pn,
                                  @RequestParam(name = "ps", required = false, defaultValue = "10") Integer ps,
                                  @RequestParam(name = "status", required = false, defaultValue = "-1") Integer status,
                                     HttpServletRequest request) {
        Member member = (Member) request.getAttribute("member");
        PageBean pageBean = meetingroomOrderService.findByPage(pn,ps,status,member);
        return new ResponseJSON().setData(pageBean);
    }

    @ResponseBody
    @RequestMapping(value = "/getMemberMeeting")
    public ResponseJSON getMemberMeeting(MemberMeetingDTO memberMeetingDTO,
                                     HttpServletRequest request) {
        Member member = (Member) request.getAttribute("member");
        PageBean pageBean = meetingroomOrderService.findByPage(memberMeetingDTO,member);
        return new ResponseJSON().setData(pageBean);
    }


    /**
     * 我的会议详情
     */
    @ResponseBody
    @RequestMapping(value = "/getOneMyMeeting")
    public ResponseJSON getOneMyMeeting(@RequestParam(name = "order_id") Integer orderId) {
        return new ResponseJSON().setData(meetingroomOrderService.queryOne(orderId));
    }


    /**
     * 查看热线
     */
    @ResponseBody
    @RequestMapping(value="/tel/detail")
    public ResponseJSON detailTel(){
        ResponseJSON responseJson = new ResponseJSON();
        ServiceTel serviceTel = serviceTelService.findById(1l);
        responseJson.setData(serviceTel);
        return responseJson;
    }


    private Integer judgeInJobTime(String time, Long faceUserId){
        Member member = memberRepository.findByFaceUserId(faceUserId);
        try {
            Boolean bool = clientParamsEntityService.judgeInJobTime(time.substring(11),member.getClientId());
            if (bool){
                return 0;
            }else {
                return 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

}

